<?php 

defined('IN_YYS')or exit('Access Denied.');
System::DOWN_App_fun("pay","pay");
System::DOWN_sys_fun("user");
System::DOWN_App_class("tocode","pay",'no');
class pay {
	private $db;
	private $huiyuans;		//会员信息
	private $MoenyCount; 	//商品总金额 
	private $shops; 		//商品信息
	private $pay_type;		//支付类型
	private $fukuan_type;	//付款类型 买商品 充值
	public $coupon_0;
	public $coupon_1;
	private $dingdan_query = true;	//订单的	mysql_qurey 结果
	public $pay_type_bank = false;
	public $coupon_ids;
	public $addressId;
	public $goods_ids;
	public $cartZgList;
	public $isZhongChou = 0;
	public $uid;
	public $scookie = null;
	public $fufen = 0;
	public $fufen_to_money = 0;	
	

						
	//初始化类数据
	//$addmoney 充值金额
	public function init($uid=null,$pay_type=null,$fukuan_type='',$addmoney='',$type=null){	
		$this->db=System::DOWN_sys_class('model');
		$this->db->tijiao_start();
		$this->members = $this->db->YOne("SELECT * FROM `@#_yonghu` where `uid` = '$uid' for update");
		$this->type = $type; //null

		if($this->pay_type_bank){//外部调用时 false
			$pay_class = $this->pay_type_bank;
			$this->pay_type =$this->db->YOne("SELECT * from `@#_payment` where `pay_class` = '$pay_class' and `pay_start` = '1'");
			$this->pay_type['pay_bank'] = $pay_type;
		}
		if(is_numeric($pay_type)){//外部调用时 true
			//pay_type：支付方式详情
			$this->pay_type =$this->db->YOne("SELECT * from `@#_payment` where `pay_id` = '$pay_type' and `pay_start` = '1'");
			$this->pay_type['pay_bank'] = 'DEFAULT';
		}

		$this->fukuan_type = $fukuan_type;
		if($fukuan_type=='go_record'){//买商品，不管余额还是第三方
			return $this->go_record();
		}
		if($fukuan_type=='addmoney_record'){		
			return $this->addmoney_record($addmoney);
		}
		return false;
	}
	
	//买商品
	private function go_record(){
		/* 开始处理购物车中的商品 */
		$uid = $this->uid;
		$yonghu = $this->db->YOne("select * from `@#_yonghu` where `uid` = '$uid'");
		$gouwuchelist = $yonghu['cartZgList'];
		$gouwuchelist = unserialize($gouwuchelist);

		$goods_ids = $this->goods_ids;
		if($goods_ids){
			$goods_ids = explode(',',$goods_ids);
			$goods_ids = array_filter($goods_ids);
			foreach($gouwuchelist as $key => $one){
				foreach($one as $k => $o){
					if(!in_array($o['shangpinId'],$goods_ids)){
						unset($gouwuchelist[$key][$k]);
					}
				}
			}
		}

		$gouwuchelist = array_filter($gouwuchelist);
	
		$shopids='';	
		foreach($gouwuchelist as $key => $val){
			foreach($val as $k => $o){
				$shopids .= $o['shangpinId'].',';
			}
		}

		$shopids = str_replace(',0','',$shopids);
		$shopids = trim($shopids,',');
		$baselist = array();		//商品信息	
		if($shopids!=NULL){
			$shopidsArray = explode(',',$shopids);
			foreach($shopidsArray as $key => $one){
				$first = array_pop(array_reverse($gouwuchelist));
				if(isset($first[0]['isZhongChou']) && $first[0]['isZhongChou'] == 1){
					//如果是众筹商品
					$shopinfo = $this->db->YOne("select * from `@#_shangpin` where `id` = '$one'");
				}else{
					$shopinfo = $this->db->YOne("select * from `@#_zg_shangpin` where `id` = '$one'");
				}
				$baselist[$shopinfo['supplierId']][$one] = $shopinfo;	
			}
		}else{
			$this->db->tijiao_rollback();
			return '购物车内没有商品!!';
		}
		echo "baselist:";
		print_r($baselist);
		$MoenyCount= 0;
		$shopguoqi = 0;
		if(count($baselist)>=1){
			$scookies_arr = array();
			$scookies_arr = $gouwuchelist;
			$scookies_arr['MoenyCount'] = 0;
			foreach($gouwuchelist as $key => $one){
				foreach($one as $k => $o){
					$MoenyCount += $o['num'] * $baselist[$key][$o['shangpinId']]['yunjiage'];
					$baselist[$key][$o['shangpinId']]['num'] = $o['num'];
					$baselist[$key][$o['shangpinId']]['buy_type'] = $o['type'];
					$baselist[$key][$o['shangpinId']]['buy_color'] = $o['color'];
					//$baselist[$key][] = $baselist[$key][$o['shangpinId']];
				}
			}

			if(count($baselist) < 1){			
				$scookies_arr = '0';
				$this->db->tijiao_rollback();
				if($shopguoqi){
					return '限时揭晓过期商品不能购买!';
				}else{
					return '购物车里没有商品!';
				}
			}
		}else{
			$scookies_arr = '0';
			$this->db->tijiao_rollback();
			return '购物车里商品已经卖完或已下架!';
		}
		/* 购物车商品处理完毕 */

		$this->MoenyCount= $MoenyCount;

		/**
		*	最多能抵扣多少钱
		*   福分抵扣（用不着）
		**/
		$this->fufen_to_money = 0;
		$this->fufen = 0;
		/* 福分抵扣完毕 */

		$this->coupon_money = 0;
		if($this->coupon_1){/* 优惠券抵扣 */
			foreach($this->coupon_1 as $key => $one){
				$coupon_info = $this->db->YOne("select * from `@#_yonghu_coupon` where `id` = '$one[0]' and `status` = '0' and `type` = '1'");
				$this->coupon_money = $this->coupon_money + $coupon_info['money'];
				//echo "<br>编号为".$one[0]."的优惠券已经抵扣".$coupon_info['money']."元。此时总抵扣：".$this->coupon_money."<br>";
			}
		}
		//echo("优惠券抵扣：".$this->coupon_money."<br>");
		
		if($this->coupon_0){/* 汇券抵扣 */
			foreach($this->coupon_0 as $key => $one){
				$coupon_info = $this->db->YOne("select * from `@#_yonghu_coupon` where `id` = '$one[0]' and `status` = '0' and `type` = '0'");
				$this->coupon_money = $this->coupon_money + $coupon_info['money'];
				//echo "编号为".$one[0]."的汇券已经抵扣".$coupon_info['money']."元"."<br>";
			}
		}
		//echo("优惠券和汇券抵扣：".$this->coupon_money."<br>");
		
		//总支付价 = 商品总价 - 总抵扣金额
		echo("商品总价：".$this->MoenyCount);
		$this->MoenyCount = $this->MoenyCount - $this->fufen_to_money - $this->coupon_money;
		echo("抵扣完后商品总价：".$this->MoenyCount);
		if($this->MoenyCount < 0){
			return '优惠券/汇券金额不得大于商品总额！';
		}
		$this->shoplist = $baselist;
		$this->scookies_arr = $scookies_arr;
		return 'ok';
	}
	

	/* 充值 data 其他数据
	* 第三方支付方式充值
	* money：充值金额
	* 返回订单编号
	*/ 
	private function addmoney_record($money=null,$data=null){		
		
		$uid=$this->members['uid'];
		$dingdancode = pay_huode_dingdan('S');
		if(!is_array($this->pay_type)){
			return 'not_pay';
		}
		$pay_type = $this->pay_type['pay_name'];
		$time = time();
		$scookies = $data;
		$score = $this->fufen;
		$type = $this->type;
		//添加充值记录
		$query = $this->db->Query("INSERT INTO `@#_yonghu_addmoney_record` (`uid`, `code`, `money`, `pay_type`, `status`,`time`,`score`,`scookies`,`orderType`,`is_zhongchou`) VALUES ('$uid', '$dingdancode', '$money', '$pay_type','未付款', '$time','$score','$scookies','$type','$this->isZhongChou')");				
		
		if($query){
			$this->db->tijiao_commit();
		}else{
			$this->db->tijiao_rollback();
			return false;
		}
		/* 添加完毕 */
		$pay_type = $this->pay_type;
		$paydb = System::DOWN_App_class($pay_type['pay_class'],'pay');
		$pay_type['pay_key'] = unserialize($pay_type['pay_key']);	

		$config=array();
		$config['id'] = $pay_type['pay_key']['id']['val'];			//支付合作ID
		$config['key'] = $pay_type['pay_key']['key']['val'];		//支付KEY
		
		$config['shouname'] = _yys('web_name');						//收款方
		$config['title'] = _yys('web_name');						//付款项目
		$config['money'] = $money;									//付款金额$money
		$config['type']  = $pay_type['pay_type'];					//支付方式：	即时到帐1   中介担保2		
		$config['ReturnUrl']  = YYS_LOCAL_PATH.'/index.php/pay/'.$pay_type['pay_class'].'_url/qiantai/';	//前台回调	
		$config['NotifyUrl']  = YYS_LOCAL_PATH.'/index.php/pay/'.$pay_type['pay_class'].'_url/houtai/';		//后台回调
		$config['pay_bank'] = $this->pay_type['pay_bank'];
		
		$config['code'] = $dingdancode;
		$config['pay_type_data'] = $pay_type['pay_key'];
		$config['orderType'] = $type;
		$config['isZhongChou'] = $this->isZhongChou;
		
		if($scookies){
			$config['payType'] = 1;
		}else{
			$config['payType'] = 0;
		}
		//print_r("即将发起第三方支付");
		$paydb->config($config);
		$paydb->send_pay();
		return $dingdancode;
	}
	
	//生成订单
	public function set_dingdan($pay_type='',$dingdanzhui='',$shoplist=''){
		$uid=$this->members['uid'];
		$uphoto = $this->members['img'];
		$weername = huode_user_name($this->members);			
		$insert_html='';
		if($this->shoplist){
			$this->shoplist = $shoplist;
		}

		if(count($this->shoplist)>1){			
			$dingdancode_tmp = 1;	//多个商品相同订单
		}else{		
			$dingdancode_tmp = 0;	//单独商品订单
		}
		
		$ip = _huode_ip_dizhi();			
	
		//订单时间
		$time = sprintf("%.3f",microtime(true));
		$zgMoney = 0;
		$this->MoenyCount = 0;
		$deal_ids = '';
		$deal_id_array = array();
		foreach($this->shoplist as $key => $shop){
			$total_money = 0;
			$dingdancode = pay_huode_dingdan($dingdanzhui);
			$this->dingdancode = $dingdancode;
			foreach($shop as $k => $s){
				$deal_id_array[] = $s['id'];
				$this->MoenyCount += $s['num'] * $s['yunjiage'];
				$total_money += $s['num'] * $s['yunjiage'];
				$deal_ids .= $s['id'].',';
				if($s['uid']){
					$isSupplier = 1;
					$supplierId = $s['uid'];
				}else{
					$isSupplier = 0;
					$supplierId = '0';
				}
				
				if($this->coupon_ids){
					$is_coupon = 1;
				}else{
					$is_coupon = 0;
				}
				$buy_type = $s['buy_type'];
				$buy_color = $s['buy_color'];
				$goods = array();
				$goods['order_sn'] = $dingdancode;
				$goods['goods_id'] = $s['id'];
				$goods['number'] = $s['num'];
				$goods['goods_price'] = $s['yunjiage'];
				$goods['total_price'] = $s['yunjiage'] * $s['num'];
				if($this->isZhongChou == 1){
					$goods['supplierPercent'] = $s['num'] * $s['yunjiage'];
				}else{
					$goods['supplierPercent'] = $s['supplierPercent'];
				}
				$goods['thumb'] = $s['thumb'];
				$goods['buy_type'] = $s['buy_type'];
				$goods['express'] = $s['isfreepost'];
				$goods['buy_color'] = $s['buy_color'];
				$goods['goods_name'] = $s['title'];
				$goods['supplier_id'] = $s['supplierId'];
				$order_item_id = insertInto($goods,'order_item');
				if(!$order_item_id){
					$this->db->tijiao_rollback();
				}
			}
			$order_data = array();
			$order_data['order_sn'] = $dingdancode;
			$goods_real_money = $total_money;
			if($this->coupon_1){
				foreach($this->coupon_1 as $c => $cou){
					$coupon_info = $this->db->YOne("select * from `@#_yonghu_coupon` where `id` = '$cou[0]' and `status` = '0' and `type` = '1'");
					$total_money = $total_money - $coupon_info['money'];
				}
			}
			$order_data['coupon_id'] = $cou;
			
			if($this->coupon_0){
				foreach($this->coupon_0 as $c => $cou1){
					$coupon_info = $this->db->YOne("select * from `@#_yonghu_coupon` where `id` = '$cou1[0]' and `status` = '0' and `type` = '0'");
					$total_money = $total_money - $coupon_info['money'];
				}
			}
			if($total_money < 0){
				return false;
			}
			$order_data['other_coupon_id'] = $cou1;
			$order_data['goods_real_money'] = $goods_real_money;
			$order_data['total_money'] = $total_money;
			$order_data['uid'] = $uid;
			$order_data['supplier_id'] = $key;
			$order_data['deal_ids'] = $deal_ids;
			$order_data['ip'] = $ip;
			if($this->addressId){
				$order_data['address_id'] = $this->addressId;
			}else{
				$order_data['address_id'] = _getcookie('addressId');
			}
			if(intval($this->isZhongChou) == 1){
				$order_data['is_zhongchou'] = 1;
			}else{
				$order_data['is_zhongchou'] = 0;
			}
			$order_data['create_time'] = time();
			$order_data['is_coupon'] = $is_coupon;

			$order_list_id = insertInto($order_data,'order_list');
			if($order_list_id){
				if($cou){
					updateSet(array('status'=>1,'order_sn'=>$dingdancode,'use_time'=>time()),'yonghu_coupon',$cou);
				}
				if($cou1){
					updateSet(array('status'=>1,'order_sn'=>$dingdancode,'use_time'=>time()),'yonghu_coupon',$cou1);
				}
				$order_array[] = $order_list_id;
				$this->db->tijiao_commit();
			}
		}
		$this->orderId = $order_array;
		/* start 清空购物车 */
		if($order_array){
			$gouwuchelist = $this->cartZgList;
			$gouwuchelist = unserialize($gouwuchelist);
			foreach($gouwuchelist as $key => $one){
				foreach($one as $k => $o){
					if(in_array($o['shangpinId'],$deal_id_array)){
						unset($gouwuchelist[$key][$k]);
					}
				}
				if(count($gouwuchelist[$key]) <= 0){
					unset($gouwuchelist[$key]);
				}
			}
			$gouwuchelist = json_encode($gouwuchelist);

			if($gouwuchelist){
				_setcookie('cartZgList',$gouwuchelist);
			}else{
				_setcookie('cartZgList',null);
			}
			return true;
		}else{
			return false;
		}
		/* end 清空购物车 */
	}
	/**
	*	开始支付
	**/
	public function start_pay($pay_checkbox,$type=null){
		if($this->MoenyCount <= 0){
			$pay_checkbox = true;
		}//总支付价格小于0，则必须用余额支付
		/* 如果用户余额 > 总价格，并选择了余额支付 */
		if($this->members['money'] >= $this->MoenyCount && $pay_checkbox){
			$uid = $this->members['uid'];	
			$uid2 = $this->members['yaoqing2'];	
			$uid3 = $this->members['yaoqing3'];
			$this->type = $type;
			$pay_1 =  $this->pay_bag();//账户里支付
			if($pay_1 != 'success'){return $pay_1;}
			$dingdancode = $this->dingdancode;
			$pay_2 = pay_go_jijin($this->goods_count_num);//欢惠券基金
			$pay_3 = pay_go_yongjin($uid,$dingdancode,$uid2,$uid3,$this->type);	//用户佣金结算
			return $this->orderId;
		}
		/* 余额支付完毕 */
		//第三方支付方式详情
		if(!is_array($this->pay_type)){
			return 'not_pay';
		}
		if(is_array($this->scookies_arr)){
			$scookie = serialize($this->scookies_arr);
		}else{
			$scookie= '0';
		}
		//是否用余额支付
		if($pay_checkbox){			
			$money = $this->MoenyCount - $this->members['money'];//价格 = 商品总价 - 账户余额
			return $this->addmoney_record($money,$scookie);
		}else{//不用余额支付
			return $this->addmoney_record($this->MoenyCount,$scookie);			
		}
		exit;		
	}
	
	//账户里支付
	private function pay_bag(){
		echo "开始账户中支付！";
		$time=time();
		$uid=$this->members['uid'];
		$fufen = System::DOWN_App_config("user_fufen",'','member');			
		$qianzui = "Sn";

		/*购买过，会员账户剩余金额*/
		$Money = $this->members['money'] - $this->MoenyCount + $this->fufen_to_money;
		$query_1 = $this->set_dingdan('账户',$qianzui,$this->shoplist);
		echo "已经设置好订单！";
		if(!$query_1){
			return $query_1;
		}
		$query_fufen = true;
		
		$pay_zhifu_name = '账户';
		if($this->fufen_to_money){
			$myfufen = $this->members['score'] - $this->fufen;
			$query_fufen = $this->db->Query("UPDATE `@#_yonghu` SET `score`='$myfufen' WHERE (`uid`='$uid')");			
			$pay_zhifu_name = '福分';
			$this->MoenyCount = $this->fufen;
		}

		//用掉优惠券
		$order_sn = $this->dingdancode;
		$now = time();
		//echo "已经用掉的优惠券编号：";
		if($this->coupon_1){
			foreach($this->coupon_1 as $c => $cou){
				$coupon_info = $this->db->Query("UPDATE `@#_yonghu_coupon` SET `use_time` = '$now',`status` = '1',`order_sn` = '$order_sn' WHERE `id` = '$cou[0]' AND `status` = '0' AND `type` = '1'");
				//echo "$cou[0],";
			}
		}
		
		if($this->coupon_0){
			foreach($this->coupon_0 as $c => $cou1){
				$coupon_info = $this->db->Query("UPDATE `@#_yonghu_coupon` SET `use_time` = '$now',`status` = '1',`order_sn` = '$order_sn' where `id` = '$cou1[0]' and `status` = '0' and `type` = '0'");
				//echo "$cou1[0],";
			}
		}
		//print_r($this->coupon_0);
		//print_r($this->coupon_1);

		//更新用户账户金额
		$query_2 = $this->db->Query("UPDATE `@#_yonghu` SET `money`='$Money' WHERE (`uid`='$uid')");			//金额
		$query_3 = $info = $this->db->YOne("SELECT * FROM  `@#_yonghu` WHERE (`uid`='$uid') LIMIT 1");
		$query_4 = $this->db->Query("INSERT INTO `@#_yonghu_zhanghao` (`uid`, `type`, `pay`, `content`, `money`, `time`,`order_sn`) VALUES ('$uid', '-1', '$pay_zhifu_name', '参与了商品', '{$this->MoenyCount}', '$time','$order_sn')");	
		
		//echo "已经更新了用户余额为$Money！原来用户余额是".$this->members['money']." 商品价格是：".$this->MoenyCount;
		$query_5 = true;
		$query_insert = true;
		$shangpinss_count_num = 0;
		foreach($this->shoplist as $shop){
			foreach($shop as $k => $s){
				if($this->isZhongChou == 1){
					$query = true;
					//$query = $this->db->Query("UPDATE `@#_shangpin` SET `maxqishu` = `maxqishu` - '$s[num]',`qishu` = `qishu` + '$s[num]' WHERE `id`='$s[id]'");
				}else{
					$query = $this->db->Query("UPDATE `@#_zg_shangpin` SET `maxqishu` = `maxqishu` - '$s[num]',`qishu` = `qishu` + '$s[num]' WHERE `id`='$s[id]'");
				}
				if(!$query){
					return '订单提交失败，error:001';
				}
				$shangpinss_count_num += $s['num'];
			}
		}

		//添加用户经验
		$jingyan = $this->members['jingyan'] + ($fufen['z_shoppay'] * $shangpinss_count_num);
		$query_jingyan = $this->db->Query("UPDATE `@#_yonghu` SET `jingyan`='$jingyan' WHERE (`uid`='$uid')");	//经验值
		
		//添加福分
		if(!$this->fufen_to_money){
			$mygoscore = $fufen['f_shoppay']*$shangpinss_count_num;
			$mygoscore_text =  "参与了{$shangpinss_count_num}人次商品";
			$myscore = $this->members['score'] + $mygoscore;		
			//$query_add_fufen_1 = $this->db->Query("UPDATE `@#_yonghu` SET `score`= '$myscore' WHERE (`uid`='$uid')");
			
			//
			$order_sn = $this->dingdancode;
			//$query_add_fufen_2 = $this->db->Query("INSERT INTO `@#_yonghu_zhanghao` (`uid`, `type`, `pay`, `content`, `money`, `time`,`order_sn`) VALUES ('$uid', '1', '福分', '$mygoscore_text', '$mygoscore', '$time','$order_sn')");
			$query_fufen = ($query_add_fufen_1 && $query_add_fufen_2);	
		}

		$order_array = $this->orderId;
		foreach($order_array as $key => $one){
			$query_6 = $this->db->Query("UPDATE `@#_order_list` SET `status` = '1' WHERE `id`='$one' and `uid` = '$uid'");
			if(!$query_6){
				return '订单提交失败，error:002';
			}
		}
		$query_7 = $this->dingdan_query;
		$query_8 = $this->db->Query("UPDATE `@#_linshi` SET `value`=`value` + $shangpinss_count_num WHERE `key`='goods_count_num'");
		$this->goods_count_num = $shangpinss_count_num;

		if($query_jingyan && $query_1 && $query_2 && $query_3 && $query_4 && $query_5 && $query_6 && $query_7 && $query_insert && $query_8){
			if($info['money'] == $Money){
				$this->db->tijiao_commit();
				return 'success';
			}else{
				$this->db->tijiao_rollback();
				exit();
				return '订单提交失败，error:003';
			}
		}else{
			$this->db->tijiao_rollback();
			return '订单提交失败，error:004';
		}
		
	}
	
	public function pay_user_go_shop($uid=null,$yonghuid=null,&$num=null){
		if(empty($uid) || empty($yonghuid) || empty($num)){
			return false;
		}
		$uid = intval($uid);$yonghuid = intval($yonghuid);$num = intval($num);		
		$this->db=System::DOWN_sys_class('model');		
		$this->db->tijiao_start();
		$huiyuan = $this->db->YOne("select * from `@#_yonghu` where `uid` = '$uid' for update");
		$shangpinsinfo = $this->db->YOne("select * from `@#_shangpin` where `id` = '$yonghuid' and `shenyurenshu` != '0' for update");
		if(!$shangpinsinfo['shenyurenshu']){
			$this->db->tijiao_rollback();
			return false;
		}
		if($shangpinsinfo['shenyurenshu'] < $num){
			$num = $shangpinsinfo['shenyurenshu'];
		}
		$if_money = $shangpinsinfo['yunjiage'] * $num;		
		$this->members = $huiyuan;		
		$this->MoenyCount = $if_money;
		$shangpinsinfo['goods_count_num'] = $num;
		$shangpinsinfo['cart_gorenci'] = $num;
	
		$this->shoplist = array();
		$this->shoplist[0] = $shangpinsinfo;
		if($huiyuan && $shangpinsinfo && $huiyuan['money'] >= $if_money){
			$uid=$this->members['uid'];	
			$uid2=$this->members['yaoqing2'];	
			$uid3=$this->members['yaoqing3'];							
			$pay_1 =  $this->pay_bag();				
			if(!$pay_1){return $pay_1;}
			$dingdancode=$this->dingdancode;	
			$pay_2 = pay_go_jijin($this->goods_count_num);
			$pay_3 = pay_go_yongjin($uid,$dingdancode,$uid2,$uid3);
			
			//星级返还
					
			//引入配置文件
			$costConfig = System::DOWN_App_config("distribution","","member");
			
			if($costConfig['disOpen']){
				startPayMargin($uid,$dingdancode);
			}
			return $pay_1;
					
		}else{
			$this->db->tijiao_rollback();
			return false;
		}		
	}
	
	
	/*新部分*/
	public function makeRandCoupon($order_sn,$total_num){
		$this->db=System::DOWN_sys_class('model');
		$this->db->tijiao_start();
		$order = $this->db->YOne("select * from `@#_order_list` where `order_sn` = '$order_sn'");
		if(!$order_sn || !$order){
			return false;
		}else{

			/*根据商户的券构造商品*/
			$shoplist = $this->db->YList("select * from `@#_shangpin` where `supplierId` = '$order[supplier_id]' and `canyurenshu` < `zongrenshu` and `shenyurenshu` > 0 order by id desc");
			
			/*如果超出剩余，则剩余部分再进行*/
			//9 = 10 - 1;
			$pay_num = $total_num - $shoplist['0']['shenyurenshu'];
			/*先支付剩余的*/
			//9，支付1
			if($pay_num > 0 ){//把这期买光了还有剩余
				$shoplist['0']['total_num'] = $shoplist['0']['shenyurenshu'];
			}else{//没剩余了，钱花完了
				$shoplist['0']['total_num'] = $total_num;
			}

			//$myfile = fopen("ctest.txt", "a");
			//fwrite(//$myfile, "当前时间".microtime(true)." 订单号：".$order_sn." 本次金额：".$total_num." 商品ID：".$shoplist['0']['id']." 商品金额：".$shoplist['0']['shenyurenshu']." 剩余金额：".$pay_num." 准备生成支付\n");
			/*进行支付生成*/
			$time = time();
			$uid = $order['uid'];
			$qianzui = "RC";
			$query_1 = $this->set_coupon_dingdan($order,'账户',$qianzui,array('0'=>$shoplist[0]));
			if($query_1 === false){
				$res = false;
				//fwrite(//$myfile, "当前时间".microtime(true)." 支付生成失败\n");
			}
			if($query_1 === true){
				$res = true;
				if($pay_num > 0){
					//fwrite(//$myfile, "当前时间".microtime(true)." 生成支付完成。正在进入下次循环\n\n");
					$this->makeRandCoupon($order_sn,$pay_num);
				}
			}
			//fclose(//$myfile);
			return $res;
		}
	}
	
	public function set_coupon_dingdan($order,$pay_type='',$dingdanzhui='',$shoplist=''){
		//$myfile = fopen("ctest.txt", "a");
		//fwrite(//$myfile, "当前时间".microtime(true)." 已进入set_coupon_dingdan\n");
		$this->db=System::DOWN_sys_class('model');
		$uid = $order['uid'];
		$members = $this->db->YOne("select * from `@#_yonghu` where `uid` = '$uid'");
		$uphoto = $members['img'];
		$weername = huode_user_name($members);			
		$insert_html='';					
		//fwrite(//$myfile, "当前时间".microtime(true)." 已进行huode_user_name\n");
		$dingdancode= pay_huode_dingdan($dingdanzhui);				
		//fwrite(//$myfile, "当前时间".microtime(true)." 已进行pay_huode_dingdan\n");
		$dingdancode_tmp = 0;
		$ip = '127.0.0.1';
		//fwrite(//$myfile, "当前时间".microtime(true)." 已进行_huode_ip_dizhi\n");
		$time = sprintf("%.3f",microtime(true));
		$this->CouponMoenyCount = 0;

		//fwrite(//$myfile, "当前时间".microtime(true)." 即将开始foreach\n");
		foreach($shoplist as $key=>$shop){
			$ret_data = array();
			$shop['codes_table'] = 'shopcodes_1';
			pay_huode_codes($shop['total_num'],$shop,$ret_data);
			$dingdan_query = $ret_data['query'];
			if(!$ret_data['query'])$dingdan_query = false;
			$codes = $ret_data['user_code'];										//得到的惠券码					
			$codes_len = intval($ret_data['user_code_len']);						//得到惠券码个数				
			$money = $codes_len * 1;												//单条商品的总价格	
			$this->CouponMoenyCount += $money;
			$status='未付款,未发货,未完成';					
			$shop['canyurenshu'] = intval($shop['canyurenshu']) + $codes_len;
			$shop['goods_count_num'] = $codes_len;
			$shop['title'] = addslashes($shop['title']);
			$bili = System::DOWN_App_config("user_fufen");
			echo "\nshop inside pay.class.php inside set_coupon_dingdan:\n";
			print_r($shop);
			echo "\n";

			if($shop['leixing']==0){
				$jia=$shop['yuanjia']*$bili["fufen_yongjinqd0"];
			}else if ($shop['leixing']==1){
				$jia=$shop['yuanjia']*$bili["fufen_yongjinqd1"];
			}else{
				$jia=$shop['yuanjia']*$bili["fufen_yongjinqd2"];
			}

			$this->coupon_shoplist[$key] = $shop;	
			$config = System::DOWN_App_config("user_fufen",'','member');//福分/经验/佣金
			$ymoney = $this->CouponMoenyCount*$config['fufen_yongjin']; //每一元返回的佣金
			$ymoney2 = $this->CouponMoenyCount*$config['fufen_yongjin2']; //每一元返回的佣金
			$ymoney3 = $this->CouponMoenyCount*$config['fufen_yongjin3']; //每一元返回的佣金
			
			if($shop['uid']){
				$isSupplier = 1;
				$supplierId = $shop['uid'];
			}else{
				$isSupplier = 0;
				$supplierId = '0';
			}
			$totalMoney = $this->CouponMoenyCount;
			if($codes_len){
				$insert_html.="('$totalMoney','$shop[expressFee]','$dingdancode','$dingdancode_tmp','$uid','$weername','$uphoto','$shop[id]','$shop[title]','$shop[qishu]','$codes_len','$money','$codes','$pay_type','$ip','$status','$time','$shop[cardId]','$shop[cardPwd]','$shop[leixing]','$shop[yuanjia]','$shop[money]','$jia','$ymoney','$ymoney2','$ymoney3','$isSupplier','$supplierId','$shop[subType]'),";		
			}
		}
		
		$sql="INSERT INTO `@#_yonghu_yys_record` (`totalMoney`,`company_money`,`code`,`code_tmp`,`uid`,`username`,`uphoto`,`shopid`,`shopname`,`shopqishu`,`gonumber`,`moneycount`,`goucode`,`pay_type`,`ip`,`status`,`time`,`cardId`,`cardPwd`,`leixing`,`yuanjia`,`money`,`zhuanhuan`,`ymoney`,`ymoney2`,`ymoney3`,`isSupplier`,`supplierId`,`newTypes`) VALUES ";
		$sql .= trim($insert_html,',');
		//file_put_contents('total_num.txt',$sql."\r\n",FILE_APPEND);

		//fwrite(//$myfile, "当前时间".microtime(true)." 待创建订单个数：".count($shoplist)." 即将执行的SQL语句。\n");
		$res = $this->db->Query($sql);
		$insertid = $this->db->last_id();
		$this->orderId = $insertid;
		//fwrite(//$myfile, "当前时间".microtime(true)." SQL语句插入的id：".$insertid."\n");
		if($insertid){
			foreach($shoplist as $shop){
				if($shop['canyurenshu'] >= $shop['zongrenshu'] && $shop['maxqishu'] >= $shop['qishu']){
					$this->db->Query("UPDATE `@#_shangpin` SET `canyurenshu`=`zongrenshu`,`shenyurenshu` = '0' where `id` = '$shop[id]'");
				}else{
					$sellnum = $this->db->YOne("select sum(gonumber) as sellnum from `@#_yonghu_yys_record` where `shopid` = '$shop[id]'");
					$sellnum = $sellnum['sellnum'];
					$shenyurenshu = $shop['zongrenshu'] - $sellnum;
					$query = $this->db->Query("UPDATE `@#_shangpin` SET `canyurenshu` = '$sellnum',`shenyurenshu` = '$shenyurenshu' WHERE `id`='$shop[id]'");
					if(!$query)$query_5=false;
				}
				$shangpinss_count_num += $shop['goods_count_num'];
			}
			$query_6 = $this->db->Query("UPDATE `@#_yonghu_yys_record` SET `status`='已付款,已发货,未完成' WHERE `code`='$dingdancode' and `uid` = '$uid'");
			$this->db->tijiao_commit();
			foreach($shoplist as $shop){
				$shop = $this->db->YOne("select * from `@#_shangpin` where `id` = '$shop[id]'");
				if($shop['canyurenshu'] >= $shop['zongrenshu'] && $shop['maxqishu'] >= $shop['qishu']){
					$this->db->tijiao_start();
					//fwrite(//$myfile, "当前时间".microtime(true)."即将进入创建商品，待创建订单个数：".count($shoplist)."\n");
					$query_insert = pay_insert_shop($shop,'add');
					if(!$query_insert){
						$this->db->tijiao_rollback();								
					}else{
						$this->db->tijiao_commit();						
					}
					$this->db->Query("UPDATE `@#_shangpin` SET `canyurenshu`=`zongrenshu`,`shenyurenshu` = '0' where `id` = '$shop[id]'");
				}
			}
		}
		////fclose(//$myfile);
		
		return true;
	}
	
}
?>